package com.leyou.order.utils;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfigImpl;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.leyou.common.exceptions.LyException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class PayHelper {

    @Autowired
    private WXPay wxPay;

    @Autowired
    private WXPayConfigImpl payConfig;

    public String getPayUrl(Long orderId, String desc, Long totalFee) {
        // 1.准备请求参数：
        Map<String, String> data = new HashMap<String, String>();
        data.put("body", desc);
        data.put("out_trade_no", orderId.toString());
        data.put("total_fee", totalFee.toString());

        data.put("spbill_create_ip", payConfig.getSpbillCreateIp());
        data.put("notify_url", payConfig.getNotifyUrl());
        data.put("trade_type", payConfig.getTradeType());  // 此处指定为扫码支付

        try {
            // 2.发起请求，得到下单结果
            Map<String, String> resp = wxPay.unifiedOrder(data);

            // 3.验证数据是否安全
            // 3.1.验证通信标识
            if("FAIL".equals(resp.get("return_code"))){
                // 记录异常
                throw new RuntimeException(resp.get("return_msg"));
            }
            // 3.2.验证业务标识
            if("FAIL".equals(resp.get("result_code"))){
                // 记录异常
                throw new RuntimeException(resp.get("err_code_des"));
            }

            checkSignature(resp);

            // 4.获取支付链接
            String codeUrl = resp.get("code_url");
            if (StringUtils.isBlank(codeUrl)) {
                // 支付地址为空，失败
                throw new RuntimeException("支付地址为空！");
            }
            return codeUrl;
        } catch (Exception e) {
            log.error("微信下单失败，原因：{}", e.getMessage(), e);
            throw new LyException(500, "微信下单失败", e);
        }
    }

    public void checkSignature(Map<String, String> resp){
        try {
            // 3.3.验证签名
            boolean boo1 = WXPayUtil.isSignatureValid(resp, payConfig.getKey(), WXPayConstants.SignType.MD5);
            boolean boo2 = WXPayUtil.isSignatureValid(resp, payConfig.getKey(), WXPayConstants.SignType.HMACSHA256);
            if(!boo1 && !boo2){
                // 验证失败，抛出异常
                throw new RuntimeException("签名错误，无效的响应！");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
